import os
from flask import Blueprint, request, render_template, jsonify, current_app
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import fail_api, success_api, table_api
from applications.common.utils.rights import authorize
from sqlalchemy import text  # 导入 text 函数
from flask_login import current_user
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import User, AdminLog
from applications.models import software_web
from applications.schemas import software_webOutSchema
from datetime import datetime
from sqlalchemy.exc import SQLAlchemyError

# from rights import flow_unit_conversion as flowConversion # 导入 flowConversion 函数 流量转换单位
bp = Blueprint('software', __name__, url_prefix='/software')




#  网站基本设置-软件发布
@bp.get('/')
@authorize("system:software:main")
def main():
    # db.create_all()

    return render_template('/system/software/main.html')

#  查询数据
@bp.get('/table')
@authorize("system:software:main")
def data():
    # site =software_web.query.filter().all()
    # 查询参数构造
    mf = ModelFilter()
    site = software_web.query.filter(mf.get_filter(software_web)).layui_paginate()
    count = site.total
    # 返回api
    return table_api(data=model_to_dicts(schema=software_webOutSchema, data=site.items), count=count)

@bp.route('/query', methods=['POST','GET'])
@authorize("system:software:main", log=True)
def query():
    
    if request.method == 'GET':
        filename = request.args.get('selectfilename')
    if request.method == 'POST':
        data = request.get_json()
        filename = data.get('selectfilename')
    # 查询参数构造
    mf = ModelFilter()
    if filename == None or filename =='':
        # 查询数据库表名称filename的filename字段及数据
        query = software_web.query.filter(mf.get_filter(software_web)).layui_paginate()
        count = query.total
    else:
        # 查询数据库表名称filename的filename字段及数据
        query = software_web.query.filter(mf.get_filter(software_web)).filter(software_web.filename.like(f'%{filename}%')).layui_paginate()
        count = query.total
    
    data = model_to_dicts(schema=software_webOutSchema, data=query.items)
    # print(data)
    # 返回api
    return table_api(msg="成功",data=data, count=count)
    
# 用户增加
@bp.get('/add')
@authorize("system:software:add", log=True)
def add():
    return render_template('system/software/add.html')

@bp.route('/save', methods=['post','get'])
@authorize("system:software:add", log=True)
def save():
    data = request.get_json()
    # 将日期字符串转换为日期对象
    upload_time_str = data.get('upload_time')
    # 插入数据
    software_data = software_web(
        filename = str_escape(data.get('filename')),
        version = str_escape(data.get('version')),
        size = str_escape(data.get('size')),
        platform = str_escape(data.get('platform')),
        description = str_escape(data.get('description')),
        url = str_escape(data.get('url')),
        upload_time = datetime.strptime(upload_time_str, '%Y-%m-%d').date(),
        enable = int(data.get('enable')),
        count = int(data.get('count'))
    )
    res_web = software_web.query.filter_by(filename=str_escape(data.get('filename'))).first()
    if res_web: return fail_api(msg="该参数已存在")
    try:
        db.session.add(software_data)
        db.session.commit()
        return success_api(msg="增加成功")
    except Exception as e:
        db.session.rollback()
        print(e)
        return fail_api(msg=f"增加失败")

#  编辑参数
@bp.route('/edit', methods=['post','get'])
@authorize("system:software:edit", log=True)
def edit():
    id = request.args.get('id')
    softwaredata = software_web.query.filter_by(id=id).first()
    # 修改upload_time的数据为datetime对象
    softwaredata.upload_time = softwaredata.upload_time.strftime('%Y-%m-%d')
    return render_template('system/software/edit.html', software=softwaredata)

#  编辑用户
@bp.route('/update', methods=['post','get'])
@authorize("system:software:edit", log=True)
def update():
    data = request.get_json()
    id = data.get('id')
    # 将日期字符串转换为日期对象
    upload_time_str = data.get('upload_time')
    data['upload_time'] = datetime.strptime(upload_time_str, '%Y-%m-%d').date()
    res = software_web.query.filter_by(id=id).update(data)
    if not res: 
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")
    


#    参数删除
# @bp.route('/remove/<int:id>', methods=['DELETE'])
@bp.route('/remove', methods=['post'])
@authorize("system:software:remove", log=True)
def delete():
    filename = request.form.get('filename')
    res = software_web.query.filter_by(filename=filename).delete()
    if not res:
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")

# 批量删除
@bp.route('/batchRemove', methods=['post'])
@authorize("system:software:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = software_web.query.filter_by(id=id).delete()
        if not res:
            return fail_api(msg="批量删除失败")
    db.session.commit()
    return success_api(msg="批量删除成功")

